package cz.apnetis.fitweb.server;

import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;

import com.google.gwt.user.client.rpc.RemoteService;

import cz.apnetis.fitweb.client.CalorieService;
import cz.apnetis.fitweb.shared.Calorie;
import cz.apnetis.fitweb.shared.dto.CalorieEntity;

// @Service
public class CalorieServiceImpl implements RemoteService, CalorieService {

  private final Random randome = new Random();

  @Autowired
  private GenericDAO<Calorie, String> calorieDao; public final GenericDAO<Calorie, String> getCalorieDao() { return calorieDao; } public final void setCalorieDao(GenericDAO<Calorie, String> calorieDao) { this.calorieDao = calorieDao; }

  @Override
  public List<Calorie> calorieList(String name) throws IllegalArgumentException {
    return getCalorieDao().getAll();
  }

  @Override
  public Calorie saveCalorie(Calorie calorie) throws IllegalArgumentException {
    CalorieEntity cal = new CalorieEntity();
    if (null != calorie.getKey() && !"".equals(calorie.getKey())) { cal.setKey(calorie.getKey()); }
    else { cal.setKeyName(calorie.getName() + String.valueOf(randome.nextLong())); }
    cal.setName(calorie.getName());
    cal.setCal(calorie.getCal());
    cal.setJoule(calorie.getJoule());

    getCalorieDao().save(cal);

    CalorieEntity result = new CalorieEntity();
    result.setName(cal.getName());
    result.setKey(cal.getKey());
    result.setJoule(cal.getJoule());
    result.setCal(cal.getCal());
    return result;
  }
}
